﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Write.Application.Command.LogicGrid;
using SC.GridManage.Domain.Models;
using Yitter.IdGenerator;

namespace SC.GridManage.API.Write.Application.Handler.LogicGrid
{
    public class CreateLogicGridHandler : IRequestHandler<CreateLogicGirdCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogicGridModel> logicGridRepo;
        private readonly IBaseRepository<DepartmentsModel> departRepo;
        private readonly IMapper mapper;

        public CreateLogicGridHandler(IBaseRepository<LogicGridModel> logicGridRepo,IBaseRepository<DepartmentsModel> departRepo, IMapper mapper)
        {
            this.logicGridRepo = logicGridRepo;
            this.departRepo = departRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 中介者处理方法-创建逻辑网格的方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateLogicGirdCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();//实例化公共响应类

            //提取命令参数中部门的id
            var departid = request.DepartmentId;

            //找到所在部分的父部门
            var selfDeparet = departRepo.QueryAsync(x => x.Id == departid).Result.FirstOrDefault();
            var parentDeparet = departRepo.QueryAsync(x => x.Id == selfDeparet.ParentId).Result.FirstOrDefault();
            if (parentDeparet == null) {
                parentDeparet = departRepo.QueryAsync(x => x.Id == 1).Result.FirstOrDefault();
            }


            //通过父部门的id找到对应的父网格对象
            var parentLogicGrid = logicGridRepo.QueryAsync(x => x.DepartmentId == parentDeparet.Id).Result.FirstOrDefault();
            if (parentLogicGrid == null) {
                parentLogicGrid = logicGridRepo.QueryAsync(x => x.DepartmentId == 1).Result.FirstOrDefault();
            }


            //判断这个部门id下是否已经存在逻辑网格
            var count = logicGridRepo.QueryAsync().Result.Where(x => x.DepartmentId == request.DepartmentId).Count();
            if (count > 0)
            {
                result.Code=GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "该部门已经添加过逻辑网格";
                return Task.FromResult(result); 
                //存在,提示不可以添加
            }
            else {
                //可以添加

                //使用mapper把命令参数映射为逻辑网格实体
                var model = mapper.Map<LogicGridModel>(request);
                model.Id = YitIdHelper.NextId();//雪花id
                model.ParentGridId = parentLogicGrid.Id;
                //使用仓储把逻辑网格实体添加到数据库
                int r= logicGridRepo.CreateAsync(model).Result;

                //判断添加受影响的行数
                if (r > 0)
                {
                    result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
                    result.Msg = "添加逻辑网格成功";
                    result.Data = r;
                }
                else {
                    result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                    result.Msg = "添加逻辑网格失败";
                    result.Data = r;
                }
            }
            return Task.FromResult(result);
        }
    }
}
